package com.blog.dao;

import com.blog.bean.Comment;
import com.blog.bean.QueryCallback;
import com.blog.bean.User;
import com.blog.util.Util;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommentDao {

    public void publishComment(int blogId, int uid, String content) throws SQLException {
        String sql = "insert into comment(blog_id, uid, content, create_time) values(" +
                blogId + ", " +
                uid + ", '" +
                content + "', '" +
                Util.getNowDateString() + "')";
        System.out.println(sql);
        JdbcUtil.execute(sql);
    }

    public List<Comment> select(int blogId) throws SQLException {
        String sql = "select * from comment " +
                "join user on comment.uid = user.id " +
                "where blog_id = " + blogId +
                " order by comment.id desc";
        System.out.println(sql);
        return (List<Comment>) JdbcUtil.executeQuery(sql, new QueryCallback() {
            @Override
            public Object doResultHandle(ResultSet resultSet) throws SQLException {
                List<Comment> list = new ArrayList<>();
                while (resultSet.next()) {
                    list.add(transformResult2Commnet(resultSet));
                }
                return list;
            }
        });
    }

    private Comment transformResult2Commnet(ResultSet resultSet) throws SQLException {
        Comment comment = new Comment();
        User user = new User();

        comment.setId(resultSet.getInt(1));
        comment.setBlogId(resultSet.getInt(3));
        comment.setContent(resultSet.getString(4));
        comment.setCreateTime(resultSet.getDate(5));

        user.setId(resultSet.getInt(6));
        user.setImg(resultSet.getString(9));
        user.setNick(resultSet.getString(10));

        comment.setUser(user);

        return comment;
    }

}
